'use strict'
let { user, messages, comment } = require('../models/m_index');
let auth = require('../tools/auth');
let index_fn = async(etc, next) => {
    etc.render('index.html')
}

let login_fn = async(etc, next) => {
    etc.render('login.html')
}

let register_fn = async(etc, next) => {

    etc.render('register.html')
}

let individual_fn = async(etc, next) => {
    let username = etc.session.username;

    //! 所有说说
    let msgs = JSON.parse(JSON.stringify(await messages.findAll({
        order: [
            ["id", "desc"]
        ]
    })))

    //! 所有评论
    let comts = JSON.parse(JSON.stringify(await comment.findAll()))

    let userIds = [];

    //! 查找msg中所有fromUserId
    msgs.forEach(row => {
        userIds.push(row.fromUserId);
    });

    //! 查找comts中所有fromUserId
    comts.forEach(row => {
        userIds.push(row.fromUserId);
    });

    //! 查找msg和comts中出现的用户
    let userAll = await user.findAll({
        where: {
            id: userIds
        }
    })

    //!根据查到的用户Id，查找用户表中的username(评论的人)
    comts.forEach(row => {
        let currentUser = userAll.filter(user => {
            return row.fromUserId === user.id;
        })[0];
        row.comUserName = currentUser.username;
    });

    //!发说说的人
    msgs.forEach(msg => {
        let msgComment = comts.filter(item => {
            return item.msgId === msg.id;
        });
        let currentUser = userAll.filter(row => {
            return row.id === msg.fromUserId;
        })[0];

        msg.msgUserName = currentUser.username;
        msg.comments = msgComment;
    });


    let obj = {
        username: username,
        msgs: msgs
    }
    etc.render('individual.html', obj)
}


let look_fn = async(etc, next) => {
    etc.render('look.html')
}

let loginDone = async(etc, next) => {
    let username = etc.request.body.username || '';
    let pwd = etc.request.body.pwd || '';
    let res = '';
    let u_one = await user.findOne({
        where: {
            username: username,
            password: pwd
        }
    }).then((row) => {
        let user = JSON.stringify(row);
        let u_two = JSON.parse(user);
        if (user !== 'null') {
            etc.session.userId = row.id;
            etc.session.username = row.username;
            res = { code: 200, msg: 'Login Success' }
        } else {
            res = { code: 1000, msg: 'Wrong username or password, please try again' }
        }
    })
    etc.body = res;
}

let registerDone = async(etc, next) => {
    let username = etc.request.body.username || '';
    let pwd = etc.request.body.pwd || '';
    let confirmPwd = etc.request.body.confirmPwd || '';
    let f_user = await user.findOne({
        where: {
            username: username
        }
    });
    console.log(JSON.stringify(f_user));
    let res;
    if (f_user) {
        res = { code: 1000, msg: 'The current user is already registered' }
    } else {
        let c_user = user.create({
            username: username,
            password: pwd
        });
        res = { code: 200, msg: 'Register Success' }
    }
    etc.body = JSON.stringify(res);
}
let login_out = async(etc, next) => {
    etc.session = null;
    etc.body = { code: 200 };
}

let say_fn = async(ctx, next) => {
    let msgSay = ctx.request.body.msgSay || '';
    let userId = ctx.session.userId;
    let msg1 = await messages.create({
        fromUserId: userId,
        content: msgSay
    });
    let data = JSON.stringify(msg1)
    ctx.body = { code: 200, data };
}

let comment_fn = async(ctx, next) => {
    let msgId = ctx.request.body.msgId || '';
    let userId = ctx.session.userId;
    let commentText = ctx.request.body.content || '';
    let msg1 = await comment.create({
        fromUserId: userId,
        msgId: msgId,
        content: commentText
    });

    // 根据fromUsreId查询对应的用户名
    let fromUser = await user.findOne({
        where: {
            id: userId
        }
    });

    //根据msgId找到fromUserId
    let msg = await messages.findOne({
        where: {
            id: msgId
        }
    });

    //根据找到fromUserId，查找相对应的用户名
    let toUser = await user.findOne({
        where: {
            id: msg.fromUserId
        }
    });

    let data = JSON.parse(JSON.stringify(msg1));

    data.fromUserName = fromUser.username;
    data.toUserName = toUser.username;

    ctx.body = { code: 200, data };
}
module.exports = {
    '/': ["get", index_fn],
    '/login': ["get", login_fn],
    '/register': ["get", register_fn],
    '/individual': ["get", auth, individual_fn],
    '/look': ["get", auth, look_fn],
    '/loginDone': ["post", loginDone],
    '/registerDone': ["post", registerDone],
    '/logout': ["post", login_out],
    '/say': ['post', say_fn],
    '/comment': ['post', comment_fn]
}